<?php

namespace App\Console\Commands\Elasticsearch;

use Illuminate\Console\Command;

class SyncModelData extends Command
{
    use Common;

    protected $signature = 'es:sync {module}';

    protected $description = '同步模型到 elasticsearch';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->module = $this->argument('module');
        $models = $this->getModels();

        $models->each(function ($class) {
            $class::chunk(10, function ($models) use ($class) {
                $indexName = $this->getIndexNameByModelClass($class);
                foreach ($models as $model) {
                    $params = [
                        'index' => $indexName,
                        'id'    => $model->id,
                        'body'  => $model->elasticsearchArray()
                    ];
                    app('es')->index($params);
                }
            });

            $this->info('文档索引完毕');
        });

        return 0;
    }
}
